from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from django_redis import get_redis_connection
from redis.client import Pipeline

from apps.users.models import User
from utils.cookiesecret import CookieSecret


# 封装登陆后合并购物车的方法
def merge_carts(user: User, request: WSGIRequest, response: HttpResponse) -> HttpResponse:
    carts_cookie = request.COOKIES.get('carts')
    if not carts_cookie:
        return response

    # {skuID:[count: int, is_selected: bool]}
    carts_cookie_dict: dict = CookieSecret.loads(carts_cookie)
    # redis   carts_userID:{sku_id:count}
    #         carts_selected_userID:{sku_id1, sku_id2}
    redis_cli: Pipeline= get_redis_connection('carts').pipeline()
    for sku_id, data_lst in carts_cookie_dict.items():
        redis_cli.hset(f"carts_{user.id}", sku_id, data_lst[0])
        redis_cli.sadd(f"carts_selected_{user.id}", sku_id) if data_lst[1] else redis_cli.srem(f"carts_selected_{user.id}", sku_id)
    redis_cli.execute()

    # 删除cookie
    response.delete_cookie('carts')
    return response
